<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="寄存器名" prop="tagname">
        <el-input
          v-model="queryParams.tagname"
          placeholder="请输入寄存器名称"
          clearable
          @keyup.enter.native="handleQuery"
          id="tagname"
        />
      </el-form-item>
      <el-form-item label="计算公式" prop="tagformula">
        <el-input
          v-model="queryParams.tagformula"
          placeholder="显示公式"
          clearable
          id="tagformula"
          disabled
          style="width: 1000px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:qstaghomepage:edit']"
        >修改</el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:qstaghomepage:export']"
        >导出</el-button>
      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="qstagList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="tagid" v-if="columns[0].visible" width="60"/>
      <el-table-column label="首页参数名称" align="center" prop="tagnameCN" v-if="columns[2].visible" width="170" :show-overflow-tooltip="true"/>
      <el-table-column label="首页参数标识" align="center" v-if="columns[1].visible" width="280" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <router-link :to="'/system/qstaghomepage-list/index/' + scope.row.tagname + '/' + myEscape(scope.row.tagformula)" class="link-type" :disabled="scope.row.tagformula === ''">
            <span>{{ scope.row.tagname }}</span>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column label="当前寄存器值" align="center" prop="tagvalue" v-if="columns[4].visible" width="100" />
      <el-table-column label="单位" align="center" prop="units" v-if="columns[5].visible" width="100" />
      <el-table-column label="公式" align="center" prop="tagformula" v-if="columns[6].visible" />
      <el-table-column label="系数" align="center" prop="itemxs" v-if="columns[12].visible" width="50"/>
      <el-table-column label="更新时间" align="center" prop="updatetime" v-if="columns[13].visible" width="150" :show-overflow-tooltip="true"/>
      <el-table-column label="操作" align="center" class-name="small-padding" width="100" >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:qstaghomepage:edit']"
          >修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport + '&dbName=' + upload.dbName"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新和初始化已经存在的项目点表数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改变量寄存器配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="寄存器名" prop="tagname">
              <el-input v-model="form.tagname" placeholder="英文名称，如“CH1-502-40001:8”，或“CHP1-506-40001”" :disabled="form.itemid === 'local'"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="中文含义" prop="tagnameCN">
              <el-input v-model="form.tagnameCN" placeholder="中文名称，如“CH1远程”，或“CHP1转速”" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="寄存地址" prop="tagvalue">
              <el-input v-model="form.tagvalue" placeholder="" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="units">
              <el-input v-model="form.units" placeholder="请输入单位" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="计算公式" prop="tagformula">
              <el-input v-model="form.tagformula" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listQsTag, getQsTag, delQsTag, addQsTag, updateQsTag, alarmLevelSelect, getDbName } from "@/api/system/qstaghomepage";
import {getToken} from "@/utils/auth";

export default {
  name: "QsTagHomepage",
  dicts: ['sys_alarm_forbid', 'sys_control_permissions', 'sys_read_type', 'sys_data_save_time', 'sys_is_alarm', 'sys_value_type','sys_is_custom_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 变量寄存器配置表格数据
      qstagList: [],
      //报警等级
      alarmLevelOptions: undefined,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 默认字典类型
      defaultTagName: "",
      defaultByTagFormulaSearch: false,
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        dbName : getDbName(),
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/qstaghomepage/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 50,
        tagname: null,
        tagnameCN: null,
        valuetype: null,
        boolType: null,
        itemdrid: null,
        itemid: null,
        itemreadtype: null,
        itemxs: null,
        savetime: null,
        units: null,
        tagdesc: null,
        alarmtag: null,
        alarmforbid: null,
        alarmgroup: null,
        alarmlevel: null,
        alarmdelay: null,
        hhValue: null,
        hhAlarmLevel: null,
        hvalue: null,
        halarmLevel: null,
        lvalue: null,
        lalarmLevel: null,
        llValue: null,
        llAlarmLevel: null,
        control: null,
        byTagFormulaSearch: null,
      },
      // 表单参数
      form: {},
      // 列信息
      columns: [
        { key: 0, label: `ID`, visible: true },
        { key: 1, label: `寄存器名称`, visible: true },
        { key: 2, label: `寄存器中文含义`, visible: true },
        { key: 3, label: `寄存器地址`, visible: true },
        { key: 4, label: `寄存器值`, visible: true },
        { key: 5, label: `单位`, visible: true },
        { key: 6, label: `公式`, visible: true },
        { key: 7, label: `值类型`, visible: true },
        { key: 8, label: `通讯驱动`, visible: true },
        { key: 9, label: `采集频率`, visible: true },
        { key: 10, label: `读写`, visible: true },
        { key: 11, label: `权限`, visible: true },
        { key: 12, label: `系数`, visible: false },
        { key: 13, label: `更新时间`, visible: true },
        { key: 14, label: `是否报警`, visible: false },
        { key: 15, label: `是否禁止`, visible: false },
        { key: 16, label: `报警分组`, visible: false },
        { key: 17, label: `报警等级`, visible: false },
        { key: 18, label: `报警延时`, visible: false },
        { key: 19, label: `高高限值`, visible: false },
        { key: 20, label: `高限值`, visible: false },
        { key: 21, label: `低限值`, visible: false },
        { key: 22, label: `低低限值`, visible: false },
        { key: 23, label: `高高限报警等级`, visible: false },
        { key: 24, label: `高限报警等级`, visible: false },
        { key: 25, label: `低限报警等级`, visible: false },
        { key: 26, label: `低低限报警等级`, visible: false },
      ],
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    const tagName = this.$route.params && this.$route.params.tagName;
    const tagFormula = this.$route.params && this.$route.params.tagformula;
    let newTagFormula = null;
    if(tagFormula != null && tagFormula.includes('|')){
      newTagFormula = tagFormula.replaceAll('|','/');
    }else{
      newTagFormula = tagFormula;
    }
    if(tagName !== undefined){
      this.getSubInfoBySubId(tagName,newTagFormula);
    }
    this.getList();
    this.getAlarmLevelSelect();
  },
  methods: {
    /** 查询变量寄存器配置列表 */
    getList() {
      this.loading = true;
      listQsTag(this.queryParams).then(response => {
        this.qstagList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询字典类型详细 */
    getSubInfoBySubId(tagName,tagFormula) {
      this.queryParams.tagname = tagName;
      this.queryParams.byTagFormulaSearch = true;
      this.defaultTagName = tagName;
      this.defaultByTagFormulaSearch = true;

      this.queryParams.tagformula = tagFormula;
    },
    /** 查询报警等级类型 */
    getAlarmLevelSelect() {
      alarmLevelSelect().then(response => {
        this.alarmLevelOptions = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        tagid: null,
        tagname: null,
        tagnameCN: null,
        drTypeCode: null,
        tagvalue: null,
        valuetype: null,
        boolType: null,
        itemdrid: null,
        itemtype: null,
        itemid: null,
        itemdradd: null,
        itemreadtype: null,
        itemxs: null,
        savetime: null,
        backtime: null,
        updatetime: null,
        units: null,
        tagdesc: null,
        tagvartype: null,
        inivalue: null,
        alarmnote: null,
        alarmtag: null,
        alarmforbid: null,
        alarmgroup: null,
        alarmtype: null,
        alarmlevel: null,
        alarmdelay: null,
        alacondition: null,
        hvalue: null,
        hhValue: null,
        lvalue: null,
        llValue: null,
        tagformula: null,
        control: null,
        meteringGroup: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.tagname = this.defaultTagName;
      this.queryParams.byTagFormulaSearch = this.defaultByTagFormulaSearch;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.tagid)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    myEscape(tagFormula){
      let newTagFormula = null;
      if(tagFormula != null && tagFormula.includes('/')){
        newTagFormula = tagFormula.replaceAll('/','|');
      }else{
        newTagFormula = tagFormula;
      }
      return newTagFormula;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加变量寄存器配置";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const tagid = row.tagid || this.ids
      getQsTag(tagid).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改变量寄存器配置";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.tagid != null) {
            updateQsTag(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addQsTag(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const tagids = row.tagid || this.ids;
      this.$modal.confirm('是否确认删除变量寄存器配置编号为"' + tagids + '"的数据项？').then(function() {
        return delQsTag(tagids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/qstaghomepage/export', {
        ...this.queryParams
      }, `全新点表初始化项目数据_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImportInit() {
      this.upload.title = "导入全新点表初始化项目";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('system/qstaghomepage/importTemplate', {
      }, `导入全新点表初始化项目_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;width:600px;padding: 10px 20px 0;'>" + response.msg + "</div>", "全新点表初始化项目导入结果", { dangerouslyUseHTMLString: true,customClass: 'el-message-box' });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
<style type="text/css">
.el-message-box {
  width: 600px; /* 设置弹框宽度为视口宽度的一半 */
}
</style>
